<template>
  <view class="adaption-input-wrapper">
    <view class="adaption-input">
      <ve-input
        type="text"
        v-bind="$attrs"
        v-model="inputVal"
        :placeholder="placeholder"
        :placeholder-style="placeholderStyle"
        :customStyle="{ width: inputWidth }"
        @input="changeInputFn"
        @blur="onBlur"
      />
    </view>
    <view :id="randomID" class="a--input">{{ modelValue || '请输入' }}</view>
  </view>
</template>

<script>
  export default {
    inheritAttrs: false,
    props: {
      modelValue: {
        type: [String, Number],
        default: '',
      },
      placeholder: {
        type: String,
        default: '请输入',
      },
      placeholderStyle: {
        type: String,
        default: 'color: #9ea5bb',
      },
    },
    data() {
      return {
        randomID: 'adaption_' + new Date().getTime(),
        inputWidth: '',
      }
    },
    watch: {
      modelValue: {
        handler() {
          this.$nextTick(() => {
            this.changeInputFn()
          })
        },
        immediate: true,
      },
    },
    options: {
      virtualHost: true,
    },
    computed: {
      inputVal: {
        set(val) {
          this.$emit('update:modelValue', val)
          this.$emit('change', val)
        },
        get() {
          return this.modelValue
        },
      },
    },
    methods: {
      onBlur(e) {
        console.log("🐳 > onBlur > e:", e);
        this.$emit('blur', e)
      },
      changeInputFn() {
        setTimeout(() => {
          const query = uni.createSelectorQuery().in(this)
          query
            .select(`#${this.randomID}`)
            .boundingClientRect((rect) => {
              if (rect) {
                // 处于不可见状态
                if (rect.width == 0) {
                  uni.$emit('getInputWidth', this.inputVal)
                } else {
                  let rectWidth = rect.width
                  if (rectWidth > 150) {
                    rectWidth = 150
                  }
                  if (this.inputVal) {
                    this.inputWidth = rectWidth + 30 + 'px'
                  } else {
                    this.inputWidth = rectWidth + 5 + 'px'
                  }
                }
              }
            })
            .exec()
        }, 0)
      },
    },
    mounted() {
      uni.$on('returnInputWidth', (width) => {
        this.inputWidth = width
      })
    },
  }
</script>

<style lang="scss" scoped>
  .adaption-input {
    font-size: 28rpx;
  }
  .a--input {
    font: inherit;
    opacity: 0;
    position: fixed;
    top: 0;
    z-index: -1;
    // color: #000;
    // z-index: 999;
    // opacity: 1;
  }
</style>
